package com.ruoyi.web.controller.camera;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.ICameraOperateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 摄像头云台操作
 *
 * @author Orange
 * @date 2021/3/9
 */
@RestController
@RequestMapping("/camera")
public class CameraOperateController {

    @Autowired
    private ICameraOperateService cameraMovementService;

    /**
     * 云台控制
     *
     * @param deviceSerial 设备序列号,存在英文字母的设备序列号，字母需为大写
     * @param channelNo    通道号 默认为 1
     * @param direction    操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     * @param speed        云台速度：0-慢，1-适中，2-快，海康设备参数不可为0 默认为 0
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Orange
     * @date 2021/3/9
     */
    @GetMapping("/start/{deviceSerial}")
    public AjaxResult movement(@PathVariable(value = "deviceSerial") String deviceSerial, @RequestParam(required = false, defaultValue = "1") String channelNo,
                               Integer direction, @RequestParam(required = false, defaultValue = "0") String speed) {
        return cameraMovementService.movement(deviceSerial, channelNo, direction, speed);

    }

    /**
     * 停止云台移动操作 建议停止云台接口带方向参数。
     *
     * @param deviceSerial 设备序列号,存在英文字母的设备序列号，字母需为大写
     * @param channelNo    通道号 默认为 1
     * @param direction    操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Orange
     * @date 2021/3/11
     */
    @GetMapping("/stop/{deviceSerial}")
    public AjaxResult stop(@PathVariable(value = "deviceSerial") String deviceSerial, @RequestParam(required = false, defaultValue = "1") String channelNo,
                           Integer direction) {
        return cameraMovementService.stop(deviceSerial, channelNo, direction);
    }

    @GetMapping("/token")
    public AjaxResult getToken() {
        return AjaxResult.success(cameraMovementService.getToken());
    }

    /**
     * TODO: 设备抓图
     *
     * @param deviceSerial 设备序列号，存在英文字母的设备序列号，字母需大写
     * @param channelNo    通道号
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author Orange
     * @date 2021/3/15
     */
    @GetMapping("/capture/{deviceSerial}")
    public void getCapture(@PathVariable(value = "deviceSerial") String deviceSerial, @RequestParam(required = false, defaultValue = "1") String channelNo, final HttpServletResponse response, final HttpServletRequest request) throws Exception {
        String preUrl = cameraMovementService.getCapture(deviceSerial, channelNo);
        OutputStream out;
        BufferedOutputStream bos ;
        BufferedInputStream bis = null;
        URL url = new URL((String)preUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        response.reset();
        response.setContentType("application/x-download;charset=GBK");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("1.jpg".getBytes("utf-8"), "iso-8859-1"));
        InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
        byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
        out = response.getOutputStream();
        bos = new BufferedOutputStream(out);
        bos.write(btImg);
        bos.flush();
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {

        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {

        }
        try {
            if (bis != null) {
                bis.close();
            }
        } catch (IOException e) {

        }
    }
    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
